﻿using System;
using Soveryn.Commerce.API;
using Soveryn.Commerce.BaseClasses;
using System.IO;
using System.Data;
using System.Collections.Generic;
using Soveryn.Commerce.Shared;
using System.Configuration;

namespace Soveryn.Commerce.Pages
{
    public partial class ProductFileDownload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            string CustomerCartSessionID = DataUtils.GetCookie(Request, "CustomerCartSessionID", "");
            if (String.IsNullOrEmpty(CustomerCartSessionID))
                ResponseForbidden();

            if(String.IsNullOrEmpty(Request.QueryString["File"]))
                ResponseForbidden();

            if (String.IsNullOrEmpty(Request.QueryString["OrderID"]))
                ResponseForbidden();

            WebsiteProperties website = WebsiteData.WebsiteDetail();

            DataSet orderDetailsDataset = null;
            Dictionary<string, object> args = new Dictionary<string, object>();
            args.Add("WebsiteAPIKey", ConfigurationManager.AppSettings["WebsiteAPIKey"]);
            args.Add("CustomerCartSessionID", CustomerCartSessionID);
            args.Add("OrderID", Request.QueryString["OrderID"]);
            APIEnvelope env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "OrderDetail", args, false, false);
            if (env.response != null)
            {
                string response = (string)env.response;
                orderDetailsDataset = new DataSet();
                orderDetailsDataset.ReadXml(new StringReader((string)env.response));
            }

            if (orderDetailsDataset.Tables.Count != 3)
                ResponseForbidden();

            DataTable orderDetailTable = orderDetailsDataset.Tables[0];
            DataTable paymentsTable = orderDetailsDataset.Tables[1];
            DataTable orderLinesTable = orderDetailsDataset.Tables[2];

            if (orderDetailsDataset == null || orderDetailTable.Rows.Count == 0 || orderLinesTable == null || orderLinesTable.Rows.Count == 0)
                ResponseForbidden();

            OrderProperties order = OrderProperties.Create(orderDetailTable.Rows[0]);

            if(DateTime.UtcNow.Subtract(order.OrderCreateDate.Value).Days > website.ProductFileExpireDays)
                ResponseForbidden();

            if(order.AmountToPay != 0)
                ResponseForbidden();


            bool download = false;
            foreach (DataRow orderLine in orderLinesTable.Rows)
            {

                if (DataUtils.GetStr(orderLine, "SKUFile").Trim().ToLower() == Request.QueryString["File"].Trim().ToLower())
                    download = true;

            }

            if (download)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Request.QueryString["File"]);
                var bytes1 = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/ProductFiles/" + Request.QueryString["File"]));
                WriteBytesToResponse(bytes1);
                Response.End();
            }
            else
                ResponseForbidden();

        }

        public void ResponseForbidden()
        {

            Response.Status = "403 Forbidden";
            Response.StatusCode = 403;
            Response.End();

        }

        public void WriteBytesToResponse(byte[] sourceBytes)
        {

            using (var sourceStream = new MemoryStream(sourceBytes, false))
            {
                sourceStream.WriteTo(Response.OutputStream);
            }

        }

    }
}